package cn.melonlib.authentication.comp.bean.impl;

import cn.melonlib.authentication.comp.bean.ProfileManager;
import cn.melonlib.authentication.comp.config.UrlConfig;
import cn.melonlib.authentication.model.entity.Profile;
import cn.melonlib.cores.graphql.comp.utils.GraphQLParam;
import cn.melonlib.cores.graphql.comp.utils.GraphQLQueryBean;
import cn.melonlib.cores.graphql.comp.utils.GraphQLTools;
import cn.melonlib.cores.graphql.model.bean.GraphQLEntityPackage;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
@ConditionalOnProperty(value = "security.auth.mode",havingValue = "api",matchIfMissing = false)
public class ApiProfileManager extends ApplicationObjectSupport implements ProfileManager {


    @Resource
    private GraphQLTools graphQLTools;

    @Resource
    private UrlConfig urlConfig;

    @Override
    public Profile getProfile() throws Exception{
        String token= WebUtils.getCookie(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(),LOGIN_USER_TOKEN).getValue();
        Profile profile = graphQLTools.query(urlConfig.getAccountApi(),
                new GraphQLQueryBean<GraphQLEntityPackage<Profile>>("accountPasswordAuthService_getAccount",
                        List.of(new GraphQLParam("token", "String", token))) {
                }, new TypeReference<Map<String, Map<String, GraphQLEntityPackage<Profile>>>>() {
                }).get("data").get("accountPasswordAuthService_getAccount").getEntity();
        return profile;
    }
}
